package com.wlts.wzy.KSUserModule.util;

import com.kuaishou.merchant.open.api.KsMerchantApiException;
import com.kuaishou.merchant.open.api.client.oauth.OauthAccessTokenKsClient;
import com.kuaishou.merchant.open.api.response.oauth.KsAccessTokenResponse;
import com.wlts.wzy.Base.BaseEntity;
import com.wlts.wzy.KSUserModule.entity.KsOauth;
import com.wlts.wzy.KSUserModule.entity.KsStoreUser;
import com.wlts.wzy.KSUserModule.service.IKsOauthService;
import com.wlts.wzy.KSUserModule.service.IKsStoreUserService;
import com.wlts.wzy.configBean.KsConfig.KsConfigInfo;
import com.wlts.wzy.expand.MyLambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
public class KsTokenUtil {

    @Autowired
    private IKsOauthService ksOauthService;
    @Autowired
    private IKsStoreUserService ksStoreUserService;

    @Scheduled(fixedDelay = 600 * 1000)//10分钟刷新一次

    public void upDateToken() {

        MyLambdaQueryWrapper<KsOauth> queryWrapper = new MyLambdaQueryWrapper<>();

        queryWrapper.eq(BaseEntity::getDelFlag, "0");

        queryWrapper.le(KsOauth::getTokenOverTime, LocalDateTime.now().plusHours(12));

        List<KsOauth> ksOauthList = ksOauthService.list(queryWrapper);

        ksOauthList.forEach(ksOauth -> {

            MyLambdaQueryWrapper<KsStoreUser> wrapper = new MyLambdaQueryWrapper<>();

            wrapper.eq(KsStoreUser::getUuid, ksOauth.getUserUuid());

            wrapper.eq(BaseEntity::getDelFlag, "0");

            KsStoreUser ksStoreUser = ksStoreUserService.getOne(wrapper);

            if (ksStoreUser != null) {
// 刷新AccessToken
                OauthAccessTokenKsClient oauthAccessTokenKsClient
                        = new OauthAccessTokenKsClient(KsConfigInfo.appKey, KsConfigInfo.appSecret);
                try {
                    KsAccessTokenResponse response = oauthAccessTokenKsClient.refreshAccessToken(ksOauth.getRefreshToken());
                    ksOauth.setAccessToken(response.getAccessToken());
                    ksOauth.setRefreshToken(response.getRefreshToken());
                    ksOauth.setExpiresIn(response.getExpiresIn());
                    ksOauth.setOpenId(response.getOpenId());
                    //access_token过期时间，单位秒，默认为172800，即48小时
                    ksOauth.setTokenOverTime(LocalDateTime.now().plusSeconds(response.getExpiresIn()));
                    ksOauth.setMessageStatus(0);
                    ksOauth.setTokenStatus(0);
                } catch (KsMerchantApiException e) {
                    e.printStackTrace();
                }
            }

        });
        if(ksOauthList.size()>0){
            ksOauthService.updateBatchById(ksOauthList);
        }

    }

}
